package com.future.controller;

import com.future.service.TradeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 模拟高并发扣减库存接口
 *
 * @author roseonly
 */
@RestController
public class StockController {

    Logger LOGGER = LoggerFactory.getLogger(StockController.class);

    @Value("${server.port}")
    private String port;

    @Autowired
    @Qualifier(value = "redisReceiver")
    private TradeService redisReceiver;


    @Autowired
    @Qualifier(value = "tradeServiceImpl")
    private TradeService tradeServiceImpl;

    @Autowired
    @Qualifier(value = "redisDistributeLockServiceImpl")
    private TradeService distributeLock;


    @Autowired
    @Qualifier(value = "zkServiceImpl")
    private TradeService zkServiceImpl;


    @PostMapping("/order")
    public String order() {
        String result = tradeServiceImpl.lock();
        return result;
    }

    /**
     * redis发布订阅，目前无法解决
     *
     * @return
     */
    @PostMapping("/order_v2")
    public String order_2() {
        String result = redisReceiver.lock();
        return result;
    }

    /**
     * 分布式锁(能实现)
     *
     * @return
     */
    @PostMapping("/order_v3")
    public String order_v3() {
        String result = distributeLock.lock();
        return result;
    }


    /**
     * zk分布式锁，可以实现防止超卖
     *
     * @return
     */
    @PostMapping("/order_zk")
    public String order_zk() {
        zkServiceImpl.lock();
        return "";
    }

    @PostMapping("/order_zk2")
    public String order_zk(@RequestParam("id") Integer id) {
        LOGGER.info("id: {}", id);
        zkServiceImpl.lock();
        return "";
    }

    @GetMapping("/getPort")
    public String getEnvironment() {
        return port;
    }

}
